package com.zhiziai.aiproxy.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author: liuxinyu06
 * @description:
 * @create: 2021-08-31
 **/
public class MD5Util {

    static char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    static String bytes2Hex(byte[] arr) {
        StringBuilder sb = new StringBuilder();
        for (byte b : arr) {
            sb.append(hexChars[(b >>> 4) & 0xF]);
            sb.append(hexChars[b & 0xF]);
        }
        return sb.toString();
    }

    public static String calcMD5(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(str.getBytes());
            return bytes2Hex(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }
    public static String encode(String source) {
        try {
            MessageDigest digester = MessageDigest.getInstance("MD5");
            byte[] sbs = source.getBytes("UTF8");
            digester.update(sbs);
            byte[] rbs = digester.digest();
            int j = rbs.length;
            char[] result = new char[j * 2];
            int k = 0;

            for(int i = 0; i < j; ++i) {
                byte b = rbs[i];
                result[k++] = hexChars[b >>> 4 & 15];
                result[k++] = hexChars[b & 15];
            }

            return new String(result);
        } catch (Exception var9) {
            return null;
        }
    }

}
